// 对象转换成 查询字符串
function querystringify(obj) {
  let str = ''
  for (let k in obj) {
    str += k + '=' + obj[k] + '&'
  }
  return str.slice(0, -1)
}

querystringify({ name: 'jack', age: 18 })
// 注册页面
const form = document.querySelector('form')
const nameInp = document.querySelector('.username')
const pwdInp = document.querySelector('.password')
const rpwdInp = document.querySelector('.rpassword')
const nickInp = document.querySelector('.nickname')
const errBox = document.querySelector('.err')

form.addEventListener('submit', e => {
  e = e || window.event
  try { e.preventDefault() } catch(err) { e.returnValue = false }
  const info = {
    username: nameInp.value,
    password: pwdInp.value,
    rpassword: rpwdInp.value,
    nickname: nickInp.value
  }
  if (!info.username || !info.password || !info.rpassword || !info.nickname) return alert('请按照规则填写表单')
  ajax({
    url: 'http://localhost:8888/users/register',
    data: querystringify(info),
    method: 'POST',
    dataType: 'json',
    success (res) {
      console.log(res);
      if (res.code === 0) {
        errBox.style.display = 'block'
      }
      if (res.code === 1) {
        errBox.style.display = 'none'
        if (window.confirm('注册成功, 点击确定跳转到登录页, 点击取消留在当前页面')) {
          window.location.href = './01.login.html'
        }
      }
    }
  })
})
